import requests
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh,en-US;q=0.9,en;q=0.8,ja;q=0.7,zh-CN;q=0.6,zh-TW;q=0.5',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'https://erp.91miaoshou.com',
    'Referer': 'https://erp.91miaoshou.com/tiktok/move_collect/history?status=success',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors', 
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
    'bx-v': '2.5.11',
    'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"macOS"',
    'x-amazon-zebra': '46abef748b8863ea5407cb60fd13af82',
    'x-front-version': '1741949632666',
    'x-timestamp': '1742003988'
}

def get_aes_key():
    char_at_codes = [
        64, 51, 52, 51, 56, 106,
        106, 59, 115, 105, 100, 117,
        102, 56, 51, 50
    ]
    chars = []
    for i in range(len(char_at_codes)):
        chars.append(chr(char_at_codes[i]))
    return ''.join(chars)

def aes_encrypt(content):
    try:
        key = get_aes_key().encode('utf-8')
        iv = b''
        # 使用PKCS7填充
        data = content.encode('utf-8')
        padded_data = pad(data, AES.block_size)
        # 创建AES-CBC模式的加密器
        cipher = AES.new(key, AES.MODE_CBC, iv.ljust(16, b'\0'))
        # 加密
        encrypted = cipher.encrypt(padded_data)
        # 转为base64
        return base64.b64encode(encrypted).decode('utf-8')
    except Exception as e:
        print(f"加密错误: {e}")
        return content
        
def ms_login(mobile, password):
    url = 'https://erp.91miaoshou.com/api/auth/account/login'
    data = {
        'mobile': aes_encrypt(mobile),
        'password': aes_encrypt(password),
        'isVerifyRemoteLogin': 'true'
    }
    response = requests.post(url, headers=headers, cookies={}, data=data)
    if 'token' not in response.json():
        raise Exception(f'【妙手】登录失败: {response.get("reason", "未知错误")}')
    return response.cookies.get('mserp', ''), response.json().get('token', '')


    
def search_ms_products(token, mserp, product_ids:list):
    url = 'https://erp.91miaoshou.com/api/platform/tiktok/move/move_collect/searchMoveCollectList'
    cookies = {
        'mserp': mserp,
        'autoLoginToken': token
    }
    data = {
        'filter[status]': 'success',
        'filter[itemId]': ','.join(product_ids),
        'pageNo': 1,
        'pageSize': len(product_ids)
    }
    response = requests.post(url, headers=headers, cookies=cookies, data=data).json()
    if 'moveCollectDetailList' not in response:
        raise Exception(f'【妙手】产品加载失败: {response.get("reason", "未知错误")}')
    result = {}
    products = response.get('moveCollectDetailList', [])
    for product in products:
        result[product['platformItemId']] = {
            'source': product['source'],
            'sourceItemId': product['sourceItemId'],
            'sourceItemUrl': product['sourceItemUrl'],
            'globalItemId': product['globalItemId'],
            'thumbnail': product['thumbnail']
        }
    return result


if __name__ == '__main__':

    # mserp, login_token = ms_login('17779188483', 'hj15797698683')
    # product_ids = ['1731073163107272161']

    mserp, login_token = ms_login('LS12345678', 'LS123456')
    product_ids = ['1731073071248278859']   

    print(mserp, login_token)

    
    products = search_ms_products(login_token, mserp, product_ids)
    import json
    print(json.dumps(products, indent=2))